import { defineStore } from 'pinia'
import { login, getUserInfo } from '../api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: {} as any,
  }),
  getters: {
      userId: (state) => state.userInfo?.userId
  },
  actions: {
    // 设置token
    setToken(token: string) {
      this.token = token
      localStorage.setItem('token', token)
    },
    // 清除token
    clearToken() {
      this.token = ''
      localStorage.removeItem('token')
      localStorage.removeItem('userId')
    },
    // 登录
    async loginAction(username: string, password: string) {
      try {
        const res = await login({ username, password })
        if (res.data && res.data.access_token) {
          this.setToken(res.data.access_token)
          return res
        }
        return Promise.reject(res)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 获取用户信息
    async getUserInfoAction() {
      try {
        const res = await getUserInfo(this.userId);
        if (res.data) {
          this.userInfo = res.data
          return res
        }
        return Promise.reject(res)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 退出登录
    logout() {
      this.clearToken()
      this.userInfo = {}
    }
  }
}) 